package com.jic.market.impl;

import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.request.MerchantRequest;
import com.jic.market.common.constant.CommonConst;
import com.jic.market.common.util.LoginService;
import com.jic.market.entity.PromotionMerchantEntity;
import com.jic.market.mapper.PromotionGiftItemEntityMapper;
import com.jic.market.mapper.PromotionMerchantEntityMapper;
import com.jic.market.orm.Pagination;
import com.jic.market.request.PromotionMerchantRequest;
import com.jic.market.request.manager.base.PromotionMerchantAndStoreIsNullRequest;
import com.jic.market.response.PageResponse;
import com.jic.market.response.PromotionMerchantResponse;
import com.jic.market.service.PromotionMerchantProductService;
import com.jic.market.service.PromotionMerchantService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 促销商家店铺关系表
 * @author : guohuayong
 * @email : 
 * @since : 2020-01-14 08:00:40
 * @version : v1.0.0
 */
@Service
public class PromotionMerchantServiceImpl implements PromotionMerchantService{

    @Autowired
    private PromotionMerchantEntityMapper curMapper;
    @Autowired
    LoginService loginService;

    @Autowired
    PromotionMerchantProductService promotionMerchantProductService;

    @Autowired
    PromotionGiftItemEntityMapper promotionGiftItemEntityMapper;
//    @Autowired
//    private ManagerMerchantApi managerMerchantApi;
    @Resource
    private ManagerMerchantApi managerMerchantApi;

    @Override
    public RestResult<Boolean> merchantAndStoreIsNull(PromotionMerchantAndStoreIsNullRequest request) {
        PromotionMerchantEntity promotionMerchantEntityQ = new PromotionMerchantEntity();
        promotionMerchantEntityQ.setPromotionId(request.getPromotionId());
        promotionMerchantEntityQ.setMerchantType(2);//店铺
        promotionMerchantEntityQ.setDeleteFlag(0);
        Integer count = curMapper.countOfPage(promotionMerchantEntityQ);
        if(count == null || count == 0){
            return RestResult.success(Boolean.TRUE);
        }
        return RestResult.success(Boolean.FALSE);
    }

    @Override
    public PageResponse<PromotionMerchantResponse> listByPage(PromotionMerchantRequest request) {
        PageResponse<PromotionMerchantResponse> responsePageResponse = new PageResponse<PromotionMerchantResponse>()
                .setPageNo(request.getPageNo())
                .setPageSize(request.getPageSize());

        Pagination pagination = Pagination.build(request);

        PromotionMerchantEntity promotionEntity = new PromotionMerchantEntity();
        AdminOperate adminOperate = request.getAdminOperate();
        promotionEntity.setPromotionId(request.getPromotionId());
        promotionEntity.setMerchantType(request.getMerchantType());
        promotionEntity.setMerchantName(request.getMerchantName());
        promotionEntity.setStorecode(request.getStorecode());
        promotionEntity.setStorename(request.getStorename());
        promotionEntity.setOrgNumber(request.getOrgNumber());
        //商家
//        if(request.getMerchantType() == 1){
//            List<Long> merchantIds = adminOperate.getMerchantIds();
//            if(CollectionUtils.isEmpty(merchantIds)){
//                return responsePageResponse.setTotalCount(0);
//            }
//            promotionEntity.setMerchantIds(merchantIds);
//        }else {
//            List<Long> storeIds = adminOperate.getStoreIds();
//            if(CollectionUtils.isEmpty(storeIds)){
//                return responsePageResponse.setTotalCount(0);
//            }
//            promotionEntity.setStoreIds(storeIds);
//        }

        List<PromotionMerchantEntity> entityList = curMapper.findOfPage(promotionEntity, pagination);
        int count = curMapper.countOfPage(promotionEntity);


        responsePageResponse.setTotalCount(count)
                .setList(entityList.stream().map(e->{
                    PromotionMerchantResponse response = new PromotionMerchantResponse();
                    response.setId(e.getId());
                    response.setPromotionId(e.getPromotionId());
                    response.setMerchantId(e.getMerchantId());
                    response.setMerchantCode(queryThirdMerchantCodeByMerchantId(e.getMerchantId()));
                    response.setMerchantType(e.getMerchantType());
                    response.setMerchantName(e.getMerchantName());
                    response.setStoreId(e.getStoreId());
                    response.setDeleteFlag(e.getDeleteFlag());
                    response.setCreateTime(e.getCreateTime());
                    response.setCreator(e.getCreator());
                    response.setCreatorName(e.getCreatorName());
                    response.setUpdateTime(new Date());
                    response.setUpdator(e.getUpdator());
                    response.setUpdatorName(e.getUpdatorName());
                    response.setOrgNumber(e.getOrgNumber());
                    response.setMerchantTypeManager(e.getMerchantTypeManager());
                    response.setStorecode(e.getStorecode());
                    response.setStorename(e.getStorename());
                    response.setStoreType(e.getStoreType());

                    return response;
                }).collect(Collectors.toList()));
        return responsePageResponse;
    }

    private String queryThirdMerchantCodeByMerchantId(Long merchantId){
        List<Long> merchantList = new ArrayList<>();
        merchantList.add(merchantId);
        RestResult<List<MerchantRequest>> resultList = managerMerchantApi.queryMerchantListByid(merchantList);
        if(null != resultList && null != resultList.getData() && !resultList.getData().isEmpty()){
            return resultList.getData().get(0).getThirdMerchantCode();
        }
        return null;
    }


    @Override
    public Integer deleteByPromotionId(PromotionMerchantRequest request) {
        PromotionMerchantEntity entity = new PromotionMerchantEntity();
        entity.setPromotionId(request.getPromotionId());
        entity.setDeleteFlag(CommonConst.DeleteEnum.DELETE.getCode());
        entity.setMerchantType(request.getMerchantType());

        return curMapper.updateByPromotionId(entity);
    }


    @Override
    public Integer saveBatchByPromotionId(List<PromotionMerchantRequest> pomotionList) {
        if (null == pomotionList || pomotionList.isEmpty()) {
            return 0;
        }
//        LoginUser currentLoginUser = loginService.getCurrentLoginUser();

        for (int i = 0; i < pomotionList.size(); i++) {
            PromotionMerchantRequest temp = pomotionList.get(i);
            PromotionMerchantEntity query = new PromotionMerchantEntity();
            query.setDeleteFlag(0);
            query.setPromotionId(temp.getPromotionId());
            query.setMerchantType(temp.getMerchantType());
            if(temp.getMerchantType() == 1){//商家
                query.setMerchantId(temp.getMerchantId());
            }else{
                query.setStoreId(temp.getStoreId());
            }
            if(curMapper.countOfPage(query) == 0){
                PromotionMerchantEntity p = new PromotionMerchantEntity();
                p.setPromotionId(temp.getPromotionId());
                p.setMerchantId(temp.getMerchantId());
                p.setMerchantType(temp.getMerchantType());
                p.setMerchantName(temp.getMerchantName());
                p.setStoreId(temp.getStoreId());
                p.setCreateTime(new Date());
//            p.setCreator(currentLoginUser.getId());
//            p.setCreatorName(currentLoginUser.getUsername());
                p.setUpdateTime(new Date());
//            p.setUpdator(currentLoginUser.getId());
//            p.setUpdatorName(currentLoginUser.getUsername());
                p.setOrgNumber(temp.getOrgNumber());
                p.setMerchantTypeManager(temp.getMerchantTypeManager());
                p.setStorename(temp.getStorename());
                p.setStorecode(temp.getStorecode());
                p.setStoreType(temp.getStoreType());
                int ret = curMapper.insert(p);
//                if (ret < 1) {
//                    return 0;
//                }
            }
        }
        return 1;
    }

    @Override
    public Integer deleteById(Long id) {
        PromotionMerchantEntity entity = new PromotionMerchantEntity();
        entity.setId(id);
        entity.setDeleteFlag(CommonConst.DeleteEnum.DELETE.getCode());

        //根据id
        PromotionMerchantEntity param = new PromotionMerchantEntity();
        param.setId(id);
        PromotionMerchantEntity merchant = curMapper.query(param);
        //商家-删除商家下所有店铺和商品（赠品）
        if(merchant.getMerchantType() == 1){
            //查询出所有storeId
            PromotionMerchantEntity storeParam = new PromotionMerchantEntity();
            storeParam.setMerchantType(2);
            storeParam.setDeleteFlag(0);
            storeParam.setMerchantId(merchant.getMerchantId());
            storeParam.setPromotionId(merchant.getPromotionId());
            List<PromotionMerchantEntity> storeList = curMapper.findAll(storeParam);
            if(CollectionUtils.isNotEmpty(storeList)){
                //删除所有店铺
                deletStoreByMerchantIdAndPromotionId(merchant.getMerchantId(), merchant.getPromotionId());
                //删除所有商品
                List<Long> storeIds = storeList.stream().map(PromotionMerchantEntity::getStoreId).collect(Collectors.toList());
                deletProductByStoreIdsAndPromotionId(storeIds, merchant.getPromotionId());
                //删除赠品
                deletGiftItemByStoreIdsAndPromotionId(storeIds, merchant.getPromotionId());
            }
        }else{
            //删除所有商品
            deletProductByStoreIdsAndPromotionId(Arrays.asList(merchant.getStoreId()), merchant.getPromotionId());
            //删除赠品
            deletGiftItemByStoreIdsAndPromotionId(Arrays.asList(merchant.getStoreId()), merchant.getPromotionId());
        }
        return curMapper.update(entity);
    }

    /**
     * 删除店铺
     * @param merchantId
     * @param promotionId
     */
    private void deletStoreByMerchantIdAndPromotionId(Long merchantId, Long promotionId){
        curMapper.deletStoreByMerchantIdAndPromotionId(merchantId, promotionId);
    }

    /**
     * 删除赠品
     * @param storeIds
     * @param promotionId
     */
    private void deletGiftItemByStoreIdsAndPromotionId(List<Long> storeIds, Long promotionId){
        promotionGiftItemEntityMapper.deletGiftItemByStoreIdsAndPromotionId(storeIds, promotionId);
    }

    /**
     * 删除商品
     * @param storeIds
     * @param promotionId
     */
    private void deletProductByStoreIdsAndPromotionId(List<Long> storeIds, Long promotionId){
        //根据stroeids 和promotionid 查询出所有spu,然后调用promotionMerchantProductService
        promotionMerchantProductService.deletProductByStoreIdsAndPromotionId(storeIds, promotionId);
    }
}